<template>
    <div class="login-wrapper">
        <div class="login-container">
            <!-- 图片轮播区域 -->
            <div class="carousel-container">
                <div class="carousel-slide" :style="{ transform: `translateX(-${currentIndex * 100}%)` }">
                    <div class="slide" v-for="(image, index) in images" :key="index">
                        <img :src="image" alt="电力安全场景">
                    </div>
                </div>
                <div class="carousel-controls" v-if="images.length > 1">
                    <button @click="prevImage" class="carousel-btn prev-btn">
                        <i class="fas fa-chevron-left"></i>
                    </button>
                    <div class="carousel-dots">
                        <span v-for="(_, index) in images"
                              :key="index"
                              @click="goToImage(index)"
                              :class="{ active: currentIndex === index }"></span>
                    </div>
                    <button @click="nextImage" class="carousel-btn next-btn">
                        <i class="fas fa-chevron-right"></i>
                    </button>
                </div>
            </div>

            <!-- 登录表单区域 -->
            <div class="form-container">
                <div class="login-header">
                    <h1><i class="fas fa-bolt"></i> 电力安全场景系统</h1>
                    <h2><i class="fas fa-sign-in-alt"></i> 用户登录</h2>
                    <p>请输入您的用户名和密码</p>
                </div>

                <form @submit.prevent="handleLogin" class="login-form">
                    <div class="form-group" :class="{ 'error': v$.username.$error }">
                        <label for="username">
                            <i class="fas fa-user"></i> 用户名
                        </label>
                        <div class="input-wrapper">
                            <input id="username"
                                   v-model="form.username"
                                   type="text"
                                   placeholder="输入用户名"
                                   @blur="v$.username.$touch()">
                        </div>
                        <span class="error-message" v-if="v$.username.$error">
                            用户名不能为空
                        </span>
                    </div>

                    <div class="form-group" :class="{ 'error': v$.password.$error }">
                        <label for="password">
                            <i class="fas fa-lock"></i> 密码
                        </label>
                        <div class="password-input">
                            <input id="password"
                                   v-model="form.password"
                                   :type="showPassword ? 'text' : 'password'"
                                   placeholder="输入密码"
                                   @blur="v$.password.$touch()">
                            <button type="button"
                                    class="toggle-password"
                                    @click="showPassword = !showPassword"
                                    :title="showPassword ? '隐藏密码' : '显示密码'">
                                <i :class="showPassword ? 'far fa-eye-slash' : 'far fa-eye'"></i>
                            </button>
                        </div>
                        <span class="error-message" v-if="v$.password.$error">
                            密码不能少于6位
                        </span>
                    </div>

                    <button type="submit" class="login-btn" :disabled="isLoggingIn">
                        <span v-if="!isLoggingIn">登 录</span>
                        <span v-else class="loading">
                            <i class="fas fa-spinner fa-spin"></i> 登录中...
                        </span>
                    </button>
                </form>
                <p class="register-link">还没有账号？ <router-link to="/register">注册</router-link></p>
            </div>
        </div>
    </div>
</template>

<script setup>
    import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
    import { useRouter } from 'vue-router'
    import useVuelidate from '@vuelidate/core'
    import { required, minLength } from '@vuelidate/validators'
    import axios from 'axios'


    // 导入本地图片（请确保图片文件存在于src/assets目录下）
    import power1 from './assets/bg/bg1.jpg'//本地导入你想要展示的图片
    import power2 from './assets/bg/bg2.jpg'
    import power3 from './assets/bg/bg3.jpg'
    import power4 from './assets/bg/bg4.jpg'

    const router = useRouter()
    const showPassword = ref(false)
    const isLoggingIn = ref(false)
    const currentIndex = ref(0)
    const intervalId = ref(null)

    // 图片数组
    //只放一张图片，注释掉其他图片
    const images = ref([power1, power2, power3, power4])//

    // 表单数据
    const form = reactive({
        username: '',
        password: ''
    })

    // 验证规则
    const rules = {
        username: { required },
        password: { required, minLength: minLength(1) }
    }

    const v$ = useVuelidate(rules, form)

    // 轮播控制方法
    const nextImage = () => {
        currentIndex.value = (currentIndex.value + 1) % images.value.length
    }

    const prevImage = () => {
        currentIndex.value = (currentIndex.value - 1 + images.value.length) % images.value.length
    }

    const goToImage = (index) => {
        currentIndex.value = index
    }

    // 自动轮播
    const startCarousel = () => {
        intervalId.value = setInterval(nextImage, 3000)
    }

    onMounted(() => {
        startCarousel()
    })

    onBeforeUnmount(() => {
        clearInterval(intervalId.value)
    })

    // 登录方法
    const handleLogin = async () => {
        const isValid = await v$.value.$validate()
        if (!isValid) return

        isLoggingIn.value = true
        try {
            const res = await axios.post('http://127.0.0.1:8080/auth/login', {
                username: form.username,
                password: form.password
            })
            localStorage.setItem('access_token', res.data.access_token)
            router.push('/')
        } catch (error) {
            alert(error.response?.data?.detail || '登录失败')
        } finally {
            isLoggingIn.value = false
        }
    }
</script>

<style scoped>
    @import'./assets/style/login.css';
</style>